/**
 * Captain
 * © 2017 Captain copyright，All rights reserved.
 * http://www.sccaptain.com.cn
 *
 * JAVA : 8
 * 文  件  名: FileUtils.java
 * 创  建  人: liutao (liu.tao@sccaptain.com.cn)
 * 创建时间: 2017年8月8日 下午2:08:27
 * 版         本: 1.0.0
 * 备         注:
 * 修订历史:
 */
package com.material.c2c.util;

import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.time.LocalDate;

/**
 * 文件操作工具类。
 *
 * @since 1.0
 * @version 1.0
 * @author liutao (liu.tao@sccaptain.com.cn)
 */
public class FileUtils {


  public static void copy(String source, String target) {
    target = target.replace("/", SystemUtil.SEPARATOR);
    int index = target.lastIndexOf(SystemUtil.SEPARATOR);
    if (-1 != index) {
      String path = target.substring(0, index);
      File file = new File(path);
      if (!file.exists()) {
        file.mkdirs();
      }

      FileOutputStream out = null;
      InputStream in = null;
      try {
        out = new FileOutputStream(new File(target.replace("/", SystemUtil.SEPARATOR)));
        in = new FileInputStream(new File(source.replace("/", SystemUtil.SEPARATOR)));
        FileCopyUtils.copy(in, out);
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        try {
          if(StringUtils.isEmpty(out)){
            out.flush();
            out.close();
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
        try {
          if(StringUtils.isEmpty(in)){
            in.close();
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  /**
   * 生成附件另存地址
   *
   * @param fjmc
   * @return
   */
  public static String mkDirOfAttachments(String fjmc) {
    LocalDate now = LocalDate.now();
    int year = now.getYear();
    int month = now.getMonthValue();
    int day = now.getDayOfMonth();
    String savePath = "/" + year + "/" + month + "/" + day + "/"
      + System.currentTimeMillis() + "_" + fjmc;
    return savePath;
  }
}
